# encoding: utf-8

module ValidateInviteCode

  module InstanceMethods

    def validate_invite_code
      return true if on_mobile
      if validate_invite_token_or_code
        self.errors.add(:sys_invite_code, '邀请码或邀请链接无效')
        return false
      end
    end

    def validate_invite_token_or_code
      if User.where(:invite_token => sys_invite_token).first.present?
        return false
      end
      InviteCode.where(:code => sys_invite_code, :used => false).first.blank?
    end
  end

    def self.included(receiver)
      receiver.class_eval do
        attr_accessor :sys_invite_code, :sys_invite_token, :on_mobile
        before_create :validate_invite_code
      end

      receiver.send :include, InstanceMethods
    end

end
